package com.lianboke.link.ad.activity;

import android.graphics.Paint;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.lianboke.link.ad.R;
import com.lianboke.link.ad.VolleyUtils.HttpCallBack;
import com.lianboke.link.ad.VolleyUtils.HttpUtil;
import com.lianboke.link.ad.app.MyApplication;
import com.lianboke.link.ad.common.CommonParams;
import com.lianboke.link.ad.dbmanager.OrderDetailsCacheUtils;
import com.lianboke.link.ad.entry.OrdetTypeTable;
import com.lianboke.link.ad.updateUtils.AppUtils;
import com.lianboke.link.ad.updateUtils.DownloadAppManager;
import com.lianboke.link.ad.utils.DateUtil;
import com.lianboke.link.ad.utils.DeviceUtils;
import com.lianboke.link.ad.utils.KLog;
import com.lianboke.link.ad.utils.MediaUtils;
import com.lianboke.link.ad.utils.ToastUtil;
import com.lianboke.link.ad.utils.imageloader.GlideLoader;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * 任务缓存详情
 */
public class OrderCacheDetailsActivity extends BaseActivity {

    @BindView(R.id.tv_order_type_title_flag)
    public TextView tv_order_type_title_flag;//名称
    @BindView(R.id.tv_order_type_title_content)
    public TextView tv_order_type_title_content;

    @BindView(R.id.tv_order_type_img_flag)
    public TextView tv_order_type_img_flag;//图标
    @BindView(R.id.iv_order_type_img_content)
    public ImageView iv_order_type_img_content;

    @BindView(R.id.tv_order_type_des_flag)
    public TextView tv_order_type_des_flag;//应用说明
    @BindView(R.id.tv_order_type_des_content)
    public TextView tv_order_type_des_content;

    @BindView(R.id.tv_order_type_manual_flag)
    public TextView tv_order_type_manual_flag;//任务手册
    @BindView(R.id.tv_order_type_manual_content)
    public TextView tv_order_type_manual_content;

    @BindView(R.id.tv_order_type_price_flag)
    public TextView tv_order_type_price_flag;//费用
    @BindView(R.id.tv_order_type_price_content)
    public TextView tv_order_type_price_content;

    @BindView(R.id.tv_order_type_jiaocheng_flag)
    public TextView tv_order_type_jiaocheng_flag;//教程
    @BindView(R.id.tv_order_type_jiaocheng_content)
    public TextView tv_order_type_jiaocheng_content;

    @BindView(R.id.tv_order_type_appstatus_flag)
    public TextView tv_order_type_appstatus_flag;//状态
    @BindView(R.id.tv_order_type_appstatus_content)
    public TextView tv_order_type_appstatus_content;

    @BindView(R.id.loading_progress)
    public ProgressBar loading_progress;

    @BindView(R.id.view_empty)
    public View view_empty;
    @BindView(R.id.view_scrollView)
    public ScrollView view_scrollView;


    @BindView(R.id.tv_order_type_createtime_content)
    public TextView tv_order_type_createtime_content;

    @BindView(R.id.tv_order_type_firsttime_content)
    public TextView tv_order_type_firsttime_content;

    @BindView(R.id.tv_order_type_lasttime_content)
    public TextView tv_order_type_lasttime_content;

    @BindView(R.id.btn_join_task)
    public Button btn_join_task;

    public OrdetTypeTable ordetTypeTableData;//任务详情信息
    private String strAppPackageName;//应用的app

    private long _id = 0l;//数据缓存id
    private String strOrderId = "";//任务id

    private boolean isHasInstallApp = false;//是否已经安装了此app


    //数据库操作订单详情
    private OrderDetailsCacheUtils orderDetailsCacheUtils ;

    //可取消的观察者
    private Disposable mDisposable;//可以取消观察者
    @Override
    public int getContentViewId() {
        return R.layout.activity_order_cache_details;
    }

    @Override
    public boolean initLocalBroadcastReceiver() {
        return true;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        setTitleBackShow(true);
        setTitleContent("已认领任务详情");
        _id = Long.valueOf(getIntent().getStringExtra("data")).longValue();
        orderDetailsCacheUtils = new OrderDetailsCacheUtils(actContext);
        //点击查看视频教程
        tv_order_type_jiaocheng_content.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(!TextUtils.isEmpty(ordetTypeTableData.getStudyurl())){
                    MediaUtils.openBrowser(actContext,ordetTypeTableData.getStudyurl());
                }else{
                    ToastUtil.show(actContext,"地址错误请联系客服...", Toast.LENGTH_LONG);
                }
            }
        });
        //认领任务
        btn_join_task.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View v) {
                if(AppUtils.hasApp(actContext,strAppPackageName)){
                    //已安装
                    isHasInstallApp = true;
                    //更新启动时间
                    orderDetailsCacheUtils.updateOrderTypeLaunchTimeByOrderId(Long.valueOf(strOrderId), DateUtil.getCurDateStr("yyyy-MM-dd"), ordetTypeTableData);
                    reportedAppInfo(3,strAppPackageName);
                    DeviceUtils.doStartApplicationWithPackageName(actContext,strAppPackageName);
                }else{
                    //未安装
                    downloadInstallAppInfo(ordetTypeTableData.getAppdownload());
                }
            }
        });
        DownloadAppManager.initDownLoadManager(actContext);
        showLoadingProgress();
        getOrderCacheDetails();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        closedCustomerLoadingDialog();
        DownloadAppManager.initDownLoadManager(actContext).destoryDownLoadService();
        if(mDisposable!=null && !mDisposable.isDisposed()){
            mDisposable.dispose();
        }
    }
    /**
     * 显示加载进度
     */
    private void showLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!= View.VISIBLE){
            loading_progress.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 隐藏加载进度
     */
    private void hideLoadingProgress(){
        if(loading_progress!=null && loading_progress.getVisibility()!=View.GONE){
            loading_progress.setVisibility(View.GONE);
        }
    }
    /**
     * 获取缓存任务详情
     */
    public void getOrderCacheDetails(){
        List<OrdetTypeTable> datas = orderDetailsCacheUtils.queryOrderTypeByOrderBy_Id(_id);
        hideLoadingProgress();
        if(datas!=null && !datas.isEmpty()){
            view_scrollView.setVisibility(View.VISIBLE);
            view_empty.setVisibility(View.GONE);
            ordetTypeTableData = datas.get(0);
            strAppPackageName = ordetTypeTableData.getAppname();
            strOrderId = String.valueOf(ordetTypeTableData.getId());
            showOrderTypeDetails();
        }else{
            view_scrollView.setVisibility(View.GONE);
            view_empty.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 显示订单详情
     */
    private void showOrderTypeDetails(){
        tv_order_type_title_content.setText(ordetTypeTableData.getName());
        GlideLoader.loadImage(ordetTypeTableData.getImg(),iv_order_type_img_content);
        tv_order_type_des_content.setText(ordetTypeTableData.getDesc());
        tv_order_type_manual_content.setText(ordetTypeTableData.getMemo());
        tv_order_type_price_content.setText(String.valueOf(ordetTypeTableData.getPrice()));
        //设置下划线
        tv_order_type_jiaocheng_content.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG );
        if(TextUtils.isEmpty(ordetTypeTableData.getStudyurl())){
            tv_order_type_jiaocheng_content.setText("无视频教程");
            tv_order_type_jiaocheng_content.setClickable(false);
        }else{
            tv_order_type_jiaocheng_content.setText("点击查看");
            tv_order_type_jiaocheng_content.setClickable(true);
        }
        //判断应用是否已安装
        if(AppUtils.hasApp(actContext,strAppPackageName)){
            //已经安装相应的app
            tv_order_type_appstatus_content.setText("已安装此任务");
            isHasInstallApp = true;
        }else {
            tv_order_type_appstatus_content.setText("未安装此任务");
            isHasInstallApp = false;
        }
        tv_order_type_createtime_content.setText(ordetTypeTableData.getCreateTime());
        tv_order_type_firsttime_content.setText(ordetTypeTableData.getFirstLaunchTime());
        tv_order_type_lasttime_content.setText(ordetTypeTableData.getLastLaunchTime());

        if(!isHasInstallApp){
            btn_join_task.setText("下载任务");
        }else{
            btn_join_task.setText("启动任务");
        }
    }

    /**
     * 下载与安装app
     */
    public void downloadInstallAppInfo(String strUrl){
        if(TextUtils.isEmpty(strUrl)){
            ToastUtil.show(actContext,"下载地址错误",Toast.LENGTH_SHORT);
        }else{
            initCustomerLoadingDialog("任务下载中...");
            List<String> datas = new ArrayList<String>();
            datas.add(strUrl);
            MyApplication.appPackNameUrlMap.put(strAppPackageName,strUrl);
            DownloadAppManager.initDownLoadManager(actContext).startDownLoadApp(datas);
        }
    }

    /**
     * 上报任务状态 1 安装、2 卸载、3 启动、4 完成
     * @param status
     * @param packagename (卸载时需要传卸载的packname)
     */
    public void  reportedAppInfo(int status,String packagename){
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(appContext));
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
        params.put("city", MyApplication.strCity);

        if(!strAppPackageName.equals(packagename)){
            params.put("taskid","");
            params.put("appname",packagename);
        }else{
            params.put("taskid",strOrderId);
            params.put("appname",strAppPackageName);
        }
        params.put("status",String.valueOf(status));
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_TYPE_ORDER_REPORTPROCESS, params, new HttpCallBack<Integer>() {

            @Override
            public void onSuccess(Integer data) {
                if(data!=null && data.intValue()==1){
                }
            }

            @Override
            public void onFail(String msg) {
            }
        });
    }
    /**
     * 安装完成后进行操作
     */
    private void installFinishFlowInfo(){
        //更新启动时间
        orderDetailsCacheUtils.updateOrderTypeLastTimeByAppName(strAppPackageName,DateUtil.getCurDateStr("yyyy-MM-dd"));
        btn_join_task.setText("启动任务");
        startAppFlowInfo();
    }
    /**
     * 启动app 操作
     */
    private void  startAppFlowInfo(){
        //上报任务操作信息
        reportedAppInfo(3,strAppPackageName);
        //更新任务的启动时间
        orderDetailsCacheUtils.updateOrderTypeLastTimeByAppName(strAppPackageName,DateUtil.getCurDateStr("yyyy-MM-dd"));
        //启动指定任务
        DeviceUtils.doStartApplicationWithPackageName(actContext,strAppPackageName);
    }
    //===============================接收器======================================

    /**
     * 接受下载的操作
     * @param action
     */
    @Override
    public void getDownLoadMyBroadcastReceiver(String action) {
        KLog.e("-------------getDownLoadMyBroadcastReceiver----------:"+action);
        if(TextUtils.isEmpty(action)){
            return;
        }
        if("android.myapp.download.downloadstart".equals(action)){
            //开始下载指定app
            Long downloadId = MyApplication.appUrlDownIdMap.get(ordetTypeTableData.getAppdownload());
            if(downloadId>0){
                setShowAndHideCustomLoadingProgress(true);
                startCheckProgress(downloadId);
            }else{
                setShowAndHideCustomLoadingProgress(false);
            }
        }else if("android.myapp.download.downloadsuccess".equals(action)){
            //下载成功
            setShowAndHideCustomLoadingProgress(false);
            updateCustomerLoadingDialog("安装中...");
            setShowAndHideCustomLoadingProgress(false);
        }else if("android.myapp.download.downloadfails".equals(action) || "android.myapp.download.downloadexecption".equals(action)){
            //下载失败
            MyApplication.appPackNameUrlMap.remove(strAppPackageName);
            closedCustomerLoadingDialog();
            ToastUtil.show(actContext,"任务下载失败，请稍后再试",Toast.LENGTH_SHORT);
        }
    }

    @Override
    public void getInstallMyBroadcastReceiver(String action) {
        //安装
        KLog.e("-------------install----------:"+action);
        if(!TextUtils.isEmpty(action) && strAppPackageName.equals(action) ){
            //关闭等待框
            closedCustomerLoadingDialog();
            //上报状态
            reportedAppInfo(1,strAppPackageName);
            //更新ui
            tv_order_type_appstatus_content.setText("已安装此任务");
            isHasInstallApp = true;
            btn_join_task.setText("启动任务");
            //安装完成后的操作
            installFinishFlowInfo();
        }
    }

    @Override
    public void getRemoveMyBroadcastReceiver(String data) {
        //卸载
        KLog.e("-------------remove----------:"+data);
        if(!TextUtils.isEmpty(data) && strAppPackageName.equals(data) ){
            tv_order_type_appstatus_content.setText("未安装此任务");
            isHasInstallApp = false;
            reportedAppInfo(2,strAppPackageName);
            btn_join_task.setText("安装任务");
        }else if(!TextUtils.isEmpty(data)){
            reportedAppInfo(2,data);
        }
    }

    //================================下载进度=============================
    //开始监听进度
    private void startCheckProgress(long downloadId) {
        Observable
                .interval(1, 10, TimeUnit.MILLISECONDS, Schedulers.io())//无限轮询,准备查询进度,在io线程执行
                .filter(times -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder != null)
                .map(i -> DownloadAppManager.initDownLoadManager(actContext).mDownloadBinder.getProgress(downloadId))//获得下载进度
                .takeUntil(progress -> progress >= 100)//返回true就停止了,当进度>=100就是下载完成了
                .distinct()//去重复
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new ProgressObserver());
    }


    //观察者
    private class ProgressObserver implements Observer<Integer> {

        @Override
        public void onSubscribe(Disposable d) {
            mDisposable = d;
        }

        @Override
        public void onNext(Integer progress) {
            setCustomLoadingDialogProgressValue(progress);
        }

        @Override
        public void onError(Throwable throwable) {
            throwable.printStackTrace();
            setShowAndHideCustomLoadingProgress(false);
            ToastUtil.showShort(actContext,"监控下载进度失败！");

        }

        @Override
        public void onComplete() {
            setCustomLoadingDialogProgressValue(100);
        }
    }
    @Override
    public void getTimerOrderdMyBroadcastReceiver(String action) {
        KLog.e("----------getTimerOrderdMyBroadcastReceiver-----------:" + action);
        if ("android.myapp.timer.orders.auto.start".equals(action)) {
            //结束本页面
            finish();
        }
    }
}
